package com.business.app.wechat.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.business.app.wechat.core.entity.UserInfoEntity;
import com.business.app.wechat.login.service.WeChatLoginService;
import com.business.app.wechat.core.entity.WeChatConstant;
import com.business.app.wechat.core.service.impl.WeChatCoreServiceImpl;
import com.business.app.wechat.login.dto.LoginResultDTO;
import com.business.app.wechat.login.dto.RegisterDTO;
import com.business.app.wechat.login.dto.RegisterResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;


/**
 * @author gchiaway
 * 日期: 2019-04-06
 * 时间: 16:11
 */
@Slf4j
@Service("weChatLoginService")
@Transactional(rollbackFor = Exception.class)
public class WeChatLoginServiceImpl extends WeChatCoreServiceImpl implements WeChatLoginService {

    /**
     * 用户管理
     */
    private final ISysUserService sysUserService;
    /**
     * 缓存管理
     */
    private final RedisUtil redisUtil;

    @Autowired
    public WeChatLoginServiceImpl(WeChatConstant weChatConstant,
                                  ISysUserService sysUserService,
                                  RedisUtil redisUtil) {
        super(weChatConstant, redisUtil);
        this.sysUserService = sysUserService;
        this.redisUtil = redisUtil;
    }

    /**
     * 注册
     *
     * @param registerDTO 注册对象
     * @return 注册结果
     */
    @Override
    public RegisterResultDTO register(RegisterDTO registerDTO) {
        RegisterResultDTO resultDTO = new RegisterResultDTO();
        SysUser user = new SysUser();
        user.setActivitiSync(CommonConstant.ACT_SYNC_0);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        user.setStatus(1);
        user.setAvatar(registerDTO.getAvatar());
        user.setUsername(registerDTO.getOpenid());
        user.setOpenid(registerDTO.getOpenid());
        user.setNickname(registerDTO.getNickname());
        user.setSex(registerDTO.getSex());
        //设置初始密码
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), "123456", salt);
        user.setPassword(passwordEncode);
        if (!sysUserService.save(user)) {
            resultDTO.setMsg("注册失败");
            resultDTO.setSuccess(false);
            return resultDTO;
        }
        return resultDTO;
    }

    /**
     * 根据openid获取用户信息
     *
     * @param openId openid
     * @return 用户信息
     */
    @Override
    public SysUser getUser(String openId) {
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getOpenid, openId);
        List<SysUser> userList = sysUserService.list(query);
        if (StringUtils.isEmpty(userList) || userList.isEmpty()) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    /**
     * 通过openid登录
     *
     * @param openId openid
     * @return 登录结果
     */
    @Override
    public LoginResultDTO login(String openId) {
        LoginResultDTO loginResultDTO = new LoginResultDTO();
        SysUser user = this.getUser(openId);
        if (StringUtils.isEmpty(user)) {
            RegisterDTO register = new RegisterDTO();
            UserInfoEntity userInfoEntity = this.getUserInfo(openId);
            register.setAvatar(userInfoEntity.getHeadImgUrl());
            register.setSex(userInfoEntity.getSex());
            register.setOpenid(userInfoEntity.getOpenId());
            register.setNickname(userInfoEntity.getNickname());
            RegisterResultDTO registerResult = this.register(register);
            if (!registerResult.getSuccess()) {
                log.error("微信 用户注册失败");
                loginResultDTO.setRegistered(false);
                loginResultDTO.setSuccess(false);
                loginResultDTO.setMsg("用户注册失败");
                return loginResultDTO;
            }
            user = this.getUser(openId);
        }
        // 生成一个token，保存用户登录状态
        // 生成token
        String token = JwtUtil.sign(user.getUsername(), user.getPassword());
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        // 设置超时时间
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
        loginResultDTO.setToken(token);
        loginResultDTO.setOpenid(user.getOpenid());
        loginResultDTO.setUserId(user.getId());
        return loginResultDTO;
    }

}
